import pickle
import re
import cPickle
import shelve

class book:
	def __init__(self,num):
		self.chapters={}
		self.num = num
class chapter:
	def __init__(self,num):
		self.verses={}
		self.num = num
	
class verse:
	def __init__(self,text,num):
		self.text = text	
		self.num = num
class bible:
	def lookup(self,book,chapter,verse):
		bookNum = 0
		if book is int:
			bookNum = book
		else:
			bookNum = self.bookNameToNum[book]
		return b.books[book].chapters[chapter].verses[verse].text

			
	def __init__(self):
		self.books = {}
		self.bookNameToNum = {}
		self.bookNumToName = {}
	def init(self,loc,bibleloc,bookToNumLoc):
		with open(loc) as f:
			currentBook = None
			currentChapter = None
			currentVerse = None	
			for line in f.readlines():
				line = (line.strip())
				m = re.match('Book\s(\d\d)\s(.+)', line)
				if m:
					currentBook = book(int(m.group(1)))
					self.bookNameToNum[ m.group(2)]= int(m.group(1))
					self.bookNumToName[int(m.group(1))] = m.group(2)
					self.books[currentBook.num]=currentBook
					continue
				m = re.match('\A(\d\d\d):(\d\d\d)\s(.+)\Z',line)
				if m:
					if int(m.group(2))==1:
						currentChapter = chapter(int(m.group(1)))
						
						currentBook.chapters[currentChapter.num]=currentChapter
					
					currentVerse = verse(m.group(3),int(m.group(2)))
					currentChapter.verses[currentVerse.num]= currentVerse
					continue
				elif not line is '':
					currentVerse.text = '%s %s' % (currentVerse.text, line)

#		store = shelve.open(bibleloc) 
#		for kb,vb in self.books.items():
#			for kc,vc in vb.chapters.items():
#				verses= []
#				for kv,ver in vc.verses.items():
#					store[str((kb,kc,kv))] = ver.text
#					verses.append(ver.text)
#				store[str((kb,kc))] = verses
#		store.close()
#		with open(bookToNumLoc,'wb') as output:
#			cPickle.dump((self.bookNameToNum,self.bookNumToName), output)


def lookup(loc,bookNum,chapter,verse=None):
	store = shelve.open(loc)
	retval = None
	if verse == None:
		retval =  store[str((bookNum,chapter))]
	else:
		retval = store[str((bookNum,chapter,verse))]
	store.close()
	return retval
def loadBookNum(loc):
	with open(loc,'rb') as output:
		return cPickle.load(output)
	
	


	
